package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //1.创建分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();
        //2.创建查询条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //3.添加查询条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //4.执行分页查询
        dishService.page(pageInfo, lambdaQueryWrapper);
        //5.对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage);
        //6.获取本次分页查询到的数据集合
        List<Dish> records = pageInfo.getRecords();
        //创建dtoList 用来保存处理好的dto数据 作为分页展示数据返回给前端
//        List<DishDto> dtoList = new ArrayList<>();
//        for (Dish dish : records) {
//            Long categoryId = dish.getCategoryId(); //获取当前菜品的分类id
//            Category category = categoryService.getById(categoryId);    //获取到分类的对象
//            String categoryName = category.getName();   //获取当前分类的名称
//            DishDto dishDto = new DishDto();    //创建dto对象
//            BeanUtils.copyProperties(dish, dishDto);    //把dish中的数据拷贝到dto中
//            dishDto.setCategoryName(categoryName);  //把分类的名称赋值给dto
//            dtoList.add(dishDto);   //把处理好的dto存储到dtoList集合中
//        }
        List<DishDto> dtoList = records.stream().map((dish) -> {
            Long categoryId = dish.getCategoryId(); //获取当前菜品的分类id
            Category category = categoryService.getById(categoryId);    //获取到分类的对象
            String categoryName = category.getName();   //获取当前分类的名称
            DishDto dishDto = new DishDto();    //创建dto对象
            BeanUtils.copyProperties(dish, dishDto);    //把dish中的数据拷贝到dto中
            dishDto.setCategoryName(categoryName);  //把分类的名称赋值给dto
            return dishDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(dtoList);    //设置处理好的dtoList给分页插件
        //7.返回查询结果
        return R.success(dtoPage);
    }

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("菜品添加成功");
    }

    /**
     * 根据id查询菜品信息并且包含口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        //根据id查询菜品信息并且包含口味信息
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //修改菜品的基本信息和口味信息
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品信息成功");
    }

    /**
     * 根据条件查询菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //1.创建查询条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.添加查询条件
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, dish.getStatus());
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //3.执行查询
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        //根据菜品的id获取对应口味信息封装到dto对象中
        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取分类的id
            Long categoryId = item.getCategoryId();
            //根据分类的id查询出分类的对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //获取当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //4.返回执行结果
        return R.success(dishDtoList);
    }

    /**
     * 修改菜品状态 （启售/停售）
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, Long[] ids){
        Dish dish = new Dish();
        dish.setStatus(status);
        for (Long id : ids) {
            dish.setId(id);
            dishService.updateById(dish);
        }
        return R.success("菜品状态修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long[] ids){
        //根据id删除 判断删除的菜品是否在启售状态 如果启售 不能删除
        //删除菜品的同时 也需要删除菜品的口味关联表
        dishService.removeWithFlavor(ids);
        return R.success("删除菜品成功");
    }
}
